package com.senlingspace.common.core.dingtalk;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.taobao.api.ApiException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 钉钉工具类
 *
 * @author lebronjames
 * @date 2024/08/19
 */
@Slf4j
@Component
@AllArgsConstructor
public class DingTalkService {

    private final Environment env;

    private final DingTalkProperties dingTalkProperties;


    /**
     * 发送文本消息
     *
     * @param content 消息内容
     * @param atAll   是否@所有人
     */
    public void sendTextMessage(String content, boolean atAll) {
        try {
            String activeProfile = env.getProperty("spring.profiles.active");
            content = activeProfile.equals("dev") ? "【开发环境】" + content
                    : activeProfile.equals("test") ? "【测试环境】" + content
                    : "【生产环境】" + content;

            Long timestamp = System.currentTimeMillis();
            String secret = dingTalkProperties.getErrMsgRobotSecret();

            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), StandardCharsets.UTF_8.displayName());

            String url = dingTalkProperties.getErrMsgRobotWebhook() + "&timestamp=" + timestamp + "&sign=" + sign;
            DingTalkClient client = new DefaultDingTalkClient(url);

            OapiRobotSendRequest req = new OapiRobotSendRequest();
            OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
            if (DingTalkMessageUtil.calculateUTF8Characters(content) > DingTalkMessageUtil.MAX_MESSAGE_LENGTH) {
                content = DingTalkMessageUtil.truncateMessageIfNeeded(content);
            }
            text.setContent(content);

            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
            at.setIsAtAll(atAll);

            req.setMsgtype("text");
            req.setText(text);
            req.setAt(at);

            client.execute(req);
        } catch (ApiException e) {
            log.error("向钉钉发送消息时发生API异常", e);
        } catch (UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException e) {
            log.error("向钉钉发送消息时发生编码异常", e);
        }
    }

}
